<template>
  <el-container>
    <el-header
      style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
      <div>
        <svg-icon class="primary" :icon-class="$route.meta.icon"/>
        <span class="primary">{{$route.meta.title}}</span>
        <el-select v-model="query.sysMchId" clearable placeholder="请选择商户" style="margin-left:20px" v-if="mchType==0||mchType==3"
                   filterable  value-key="id" :filter-method="querySysmch" @change="changeSysMch" >
          <el-option v-for="item in mchIdOptions" :key="item.id"   :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="header-button-container">
        <el-button :icon="queryType? 'el-icon-search':'el-icon-close'" type="primary" @click="chooseClick">{{queryType == false?'隐藏':'查询'}}</el-button>
        <el-button v-permission="['receiver.add']" icon="el-icon-plus" type="primary" style="margin-left: 10px"
                   @click="addClick">新增
        </el-button>
      </div>
    </el-header>
    <div class="pd10">
      <div style="margin-bottom: 10px;display: flex;align-items: center;justify-content: space-between;" v-show="queryType == false">
        <div>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-select style="width: 100%;" v-model="query.memberId" clearable placeholder="请选择用户名" filterable :filter-method="queryMember">
                  <el-option v-for="item in memberIdOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select style="width: 100%;" v-model="query.mapLineId" clearable placeholder="请选择送货线路" filterable :filter-method="queryMapLine">
                  <el-option v-for="item in mapLineIdOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-input prefix-icon="el-icon-search" placeholder="收货人" clearable v-model="query.consignee"></el-input>
            </el-col>
            <el-col :span="6">
              <el-input type="number" prefix-icon="el-icon-search" placeholder="联系方式" clearable v-model="query.phone"></el-input>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-button style="margin-left: 10px" icon="el-icon-search" type="primary" :loading="queryClicked" @click="queryClick">查询</el-button>
          <el-button style="margin-left: 10px" icon="el-icon-refresh-right" type="info" :loading="resetClicked" @click="resetClick">重置</el-button>
        </div>
      </div>
      <el-table
        :data="receiverForm"
        border
        stripe
        v-loadMore="[payLoads,'receiver-list']"
        :height="curHeight"
        style="width: 100%">
        <el-table-column
          label="用户名"
          align="left"
          prop="memberName"
          width="150"
        >
        </el-table-column>
        <el-table-column
          label="收货人"
          align="left"
          prop="consignee"
          width="100"
        >
        </el-table-column>
        <el-table-column
          label="联系电话"
          align="left"
          prop="phone"
          width="110"
        >
        </el-table-column>
        <el-table-column
          label="收货地址"
          align="left"
          prop="areaName"
          width="200"
        >
        </el-table-column>
        <el-table-column
          label="详细地址"
          align="left"
          prop="address"
        >
          <template slot-scope="scope">
            {{ scope.row.address + scope.row.roomNumber }}
          </template>
        </el-table-column>
        <el-table-column
          label="默认地址"
          align="center"
          prop="isDefault"
          width="80"
        >
          <template slot-scope="scope">
            {{scope.row.isDefault? '是':''}}
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="小区/大楼"
          align="left"
          prop="building"
          width="100"
        >
        </el-table-column>
        <el-table-column
          label="门牌号码"
          align="left"
          prop="roomNumber"
          width="80"
        >
        </el-table-column> -->
        <el-table-column label="操作" fixed="right" align="center" width="80">
          <template slot-scope="scope">
            <div>
              <el-tooltip v-permission="['receiver.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                <a @click="editClick(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit"></i>
                </a>
              </el-tooltip>
              <el-tooltip v-permission="['receiver.del']" class="item" effect="dark" content="删除" placement="top-start">
                <a style="margin-left: 10px" @click="deleteReceiver(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="loadReceiver"></pagination>
    </el-footer>
  </el-container>
</template>

<script>
  import loadMore from '@/utils/loadMore.js'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {list, del, find, save, update} from '@/api/receiver'
  import utils from '../../utils/utils.js'
  import Pagination from '@/components/Pagination';
  import SingleUpload from '@/components/Upload/singleUpload'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import { list as memberList } from '@/api/member'
  import { list as mapLineList } from '@/api/mapLine'
  import {EventBus} from '@/api/eventBus'
  import { getInfo, list as sysMchList } from '@/api/sysMch'

  export default {
    directives: {permission,loadMore},
    name: 'receiver-list',
    activated() {
      this.payLoads = new Date().getTime();
    },
    data() {
      return {
        queryType: true,
        mchIdOptions:[],
        mchType:'',
        query: {
          consignee: '',
          address: '',
          sysMchId:'',
          memberId: '',
          phone: '',
          mapLineId: ''
        },
        keyword: {
          consignee: '',
          address: '',
          memberId: '',
          phone: '',
          mapLineId: ''
        },
        queryClicked: false,
        resetClicked: false,
        memberMark: false, // 防抖
        memberIdOptions: [],
        mapLineMark: false,
        mapLineIdOptions: [],
        clicked: false,
        curHeight: null,
        payLoads:'',
        receiverForm: [],
        pageNum: 1,
        pageSize: 20,
        total: 0
      }
    },
    components: {Pagination, SingleUpload, Distpicker},
    created() {
      this.loadSysmch('')
      this.loadMch()
      this.loadReceiver()
      EventBus.$on('receiver-add', res => { // 监听添加
        this.loadReceiver()
      })
      EventBus.$on('receiver-edit', res => { // 监听修改
        // 更新列表数组
        for (var i = 0; i < this.receiverForm.length; i++) {
          if (this.receiverForm[i].id == res.id) {
            this.$set(this.receiverForm, i, res)
          }
        }
      })
    },
    filters: {},
    mounted() {
      this.comeIn()
      this.beforeMount()
      this.queryMember()
      this.queryMapLine()
    },
    methods: {
      loadSysmch(query){
        sysMchList({ name: query }).then(res => {
          this.mchIdOptions = res.data.data.filter(val => { return val.mchType === 3||val.mchType === 1 })
        }).catch(err => { console.log(err) })
      },
      changeSysMch(){
        this.loadReceiver()
      },
      querySysmch(query){
        this.loadSysmch(query)
      },
      loadMch(){
        getInfo().then(res=>{
          this.mchType=res.data.mchType
        })
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 266//减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 220//减去页面上固定高度height
            }
          })();
        };
      },
      comeIn() {
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220//减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266//减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220//减去页面上固定高度height
        }
      },
      queryClick() {
        this.queryClicked = true
        this.keyword = this.query;
        this.pageNum = 1
        this.loadReceiver()
      },
      resetClick() {
        this.resetClicked = true
        this.query.consignee = '';
        this.query.address = '',
        this.query.memberId = '',
        this.query.phone = ''
        this.query.mapLineId = ''
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadReceiver()
      },
      queryMember (query) { // 防抖搜索客户
        clearTimeout(this.memberMark)
        this.memberMark = setTimeout(() => {
          this.memberIdOptions = []
          memberList({name: query}).then(res => {
            this.memberIdOptions = res.data.data
          }).catch(err => {
            console.log(err)
          })
        }, 300)
      },
      queryMapLine (query) { // 防抖搜索线路
        clearTimeout(this.mapLineMark)
        this.mapLineMark = setTimeout(() => {
          this.mapLineIdOptions = []
          mapLineList({name: query}).then(res => {
            console.log(res)
            this.mapLineIdOptions = res.data.data
          }).catch(err => {
            console.log(err)
          })
        }, 300)
      },
      //新增
      addClick() {
        this.$router.push({
          path: '/receiver/add'
        })
      },
      //  编辑
      editClick(row) {
        this.$router.push({
          path: '/receiver/edit?id=' + row.id +'&memberId=' + row.memberId
        })
      },
      loadReceiver() {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageNum', _this.pageNum);
        params.append('pageSize', _this.pageSize);
        params.append('consignee', _this.keyword.consignee);
        params.append('address', _this.keyword.address);
        params.append('memberId', _this.keyword.memberId);
        params.append('mchId',this.query.sysMchId)
        params.append('phone', _this.keyword.phone);
        params.append('mapLineId', _this.keyword.mapLineId);
        list(params).then(response => {
          console.log(response)
          this.queryClicked = false
          this.resetClicked = false
          _this.receiverForm = response.data.data
          _this.total = response.data.total
        }).catch(error => {
          this.queryClicked = false
          this.resetClicked = false
          console.log('error!!')
        });
      },
      deleteReceiver(data) {
        console.log(data)
        var _this = this;
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(data.id).then(response => {
            console.log(response)
            _this.receiverForm.forEach(function (item, index) {
              if (item.id == data.id) {
                _this.receiverForm.splice(index, 1)
              }
            });
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {

        })
      }
    }
  }
</script>
<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  /deep/ .el-dialog__header {
    border: 1px solid #eeeeee !important;
    padding: 15px !important;
  }

  /deep/ .el-dialog__body {
    padding: 0px 20px !important;
  }

  .popup_content {
    padding-bottom: 0px !important;
  }
</style>
